package dongze.com.ckdj.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import dongze.com.ckdj.R;
import dongze.com.ckdj.dagger.component.VehicleComponent;
import dongze.com.ckdj.data.entity.response.InspectionSectionResponse;
import dongze.com.ckdj.data.entity.response.QueryChildPointsResponse;
import dongze.com.ckdj.data.entity.response.QueryOtherPointsResponse;
import dongze.com.ckdj.data.entity.response.User;
import dongze.com.ckdj.data.entity.response.VehicleInformationDetail;
import dongze.com.ckdj.event.RefreshEvent;
import dongze.com.ckdj.map.MapUtil;
import dongze.com.ckdj.util.MyLog;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.observers.DisposableObserver;


/**
 * 根据12宫格选择质损部位
 *
 * @author Renxiaoxiao 2017.08.11
 * @version 1.0
 */
public class SelectCheckPointActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "SelectCheckPointActivit";
    private static final int POINT = 13;
    private static final int PART = 14;
    private static final int ENCLOSURE = 15;

    private Map<String, String> informations = new HashMap<>();
    private Map<String, String> pointMap = new HashMap<>();
    private List<QueryChildPointsResponse> mPointList = new ArrayList<>();
    private List<QueryOtherPointsResponse> mOtherList = new ArrayList<>();
    private String[] points;

    MapUtil mapUtil;

    @BindView(R.id.point13)
    Button mBtnPoint;
    @BindView(R.id.point14)
    Button mBtnPart;
    @BindView(R.id.point15)
    Button mBtnEnclosure;
    @BindView(R.id.check_table)
    TableLayout mTable;
    @BindView(R.id.request_process)
    ViewGroup mProcessing;

    @Inject
    VehicleInformationDetail vehicleInformationDetail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mapUtil = new MapUtil(getAppCompenent());

        if (getComponent(VehicleComponent.class) != null) {
            getComponent(VehicleComponent.class).inject(this);
        } else {
            finish();
            return;
        }

        setContentView(R.layout.activity_select_check_point);
        ButterKnife.bind(this);
        initData();

        bindPointId();
    }

    @Override
    protected void onDestroy() {
        mapUtil.dispose();
        super.onDestroy();
        EventBus.getDefault().post(new RefreshEvent(true));
    }

    private void initData() {
        Intent intent = getIntent();
        if (intent != null && intent.getExtras() != null) {
            informations.put("voyageNo", intent.getExtras().getString("voyageNo", ""));
            informations.put("model", intent.getExtras().getString("model", ""));
            informations.put("modelCode", intent.getExtras().getString("modelCode", ""));
            informations.put("uri", intent.getExtras().getString("uri", ""));
        } else {
            new android.app.AlertDialog.Builder(this)
                    .setTitle("错误")
                    .setMessage("没有传递extras数据")
                    .setCancelable(false)
                    .setNegativeButton("退出", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    }).create()
                    .show();
        }

        setPointMap();
    }

    private void setPointMap() {
        pointMap.put("备胎缺失", "Lack of spare tire");
        pointMap.put("急救包缺失", "An emergency package is missing");
        pointMap.put("三脚架缺失", "Tripod missing");
        pointMap.put("补胎液缺失", "anhydration");
        pointMap.put("千斤顶缺失", "Lack of jack");
        pointMap.put("工具包缺失", "Tool kit missing");
        pointMap.put("防盗螺母缺失", "Lack of theft nut");
        pointMap.put("充气泵缺失", "Air pump loss");
        pointMap.put("拖车钩缺失", "towing");
        pointMap.put("地毯缺失", "The carpet is missing");
    }

    /**
     * 给十三个父部位赋id值
     */
    private void bindPointId() {
        mBtnPoint.setOnClickListener(this);
        mBtnPart.setOnClickListener(this);
        mBtnEnclosure.setOnClickListener(this);
        mBtnPoint.setTag(POINT);
        mBtnPart.setTag(PART);
        mBtnEnclosure.setTag(ENCLOSURE);
        for (int i = 0; i < mTable.getChildCount(); i++) {
            TableRow row = (TableRow) mTable.getChildAt(i);
            for (int j = 0; j < row.getChildCount(); j++) {
                ImageView img = (ImageView) row.getChildAt(j);
                img.setOnClickListener(this);
                img.setTag(i * 3 + j + 1);
            }
        }
    }

    @Override
    public void onClick(View v) {
        final int id = (int) v.getTag();
        MyLog.d(TAG, "onClick: v.Id = " + id);
        switch (id) {
            case 14:
//                setPartPoints();
//                AlertDialog.Builder builder= new AlertDialog.Builder(SelectCheckPointActivity.this);
//                builder.setTitle("请选择具体检查部位")
//                        .setItems(points, new DialogInterface.OnClickListener() {
//
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                diaMyLog.dismiss();
//                                AddMassLossRecordActivity.actionStart(SelectCheckPointActivity.this, String.valueOf(id), "",
//                                        points[which], pointMap.get(points[which]), informations.get("voyageNo"),
//                                        informations.get("model"), informations.get("modelCode"), informations.get("uri"));
//                            }
//                        }).show();
                getOtherPoints(String.valueOf(id), "1");
                break;
            case 15:
//                AddMassLossRecordActivity.actionStart(SelectCheckPointActivity.this, String.valueOf(id), "",
//                        "", "", informations.get("voyageNo"),
//                        informations.get("model"), informations.get("modelCode"), informations.get("uri"));
                getOtherPoints(String.valueOf(id), "2");
                break;
            default:
                getChildPoints(String.valueOf(id));
                break;

        }
    }

    private void setPartPoints() {
        points = new String[pointMap.size()];
        int i = 0;
        Iterator iter = pointMap.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            points[i] = (String) entry.getKey();
            i++;
        }

    }

    /**
     * 获取配件、附件包
     *
     * @param parentId
     */
    private void getOtherPoints(final String parentId, String type) {
        mapUtil.getOtherPoints(type, vehicleInformationDetail.getBrand_code(), new DisposableObserver<List<QueryOtherPointsResponse>>() {

            @Override
            protected void onStart() {
                super.onStart();
                changeVisibilty(true);
            }

            @Override
            public void onNext(List<QueryOtherPointsResponse> value) {
                mOtherList = value;
                if (mOtherList != null && mOtherList.size() > 0) {
                    if ("14".equals(parentId)) {
                        points = new String[value.size()];
                        for (int i = 0; i < value.size(); i++) {
                            points[i] = value.get(i).getName_ch();
                        }
                        selectChildPoint(parentId);
                    } else if ("15".equals(parentId)) {
                        Intent intent = new Intent(SelectCheckPointActivity.this, AddMassLossRecordActivity.class);
                        intent.putExtra("parentId", parentId);
                        intent.putExtra("childId", "");
                        intent.putExtra("childName", "");
                        intent.putExtra("enName", "");
                        intent.putExtra("voyageNo", informations.get("voyageNo"));
                        intent.putExtra("model", informations.get("model"));
                        intent.putExtra("modelCode", informations.get("modelCode"));
                        intent.putExtra("uri", informations.get("uri"));
                        intent.putParcelableArrayListExtra("list", (ArrayList<? extends Parcelable>) mOtherList);
                        startActivity(intent);
                    } else {
                        showAlert("数据异常");
                    }
                } else {
                    showAlert("没有获取到相关数据");
                }
            }

            @Override
            public void onError(Throwable e) {
                changeVisibilty(false);
                if (!isFinishing()) {
                    new AlertDialog.Builder(SelectCheckPointActivity.this)
                            .setTitle("错误" + e.getMessage())
                            .setMessage(e.getLocalizedMessage())
                            .create()
                            .show();
                }
            }

            @Override
            public void onComplete() {
                changeVisibilty(false);
            }
        });
    }

    private void showAlert(String msg) {
        if (!isFinishing()) {
            new AlertDialog.Builder(SelectCheckPointActivity.this)
                    .setTitle("错误")
                    .setMessage(msg)
                    .setCancelable(false)
                    .setNegativeButton("退出", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    }).create()
                    .show();
        }
    }

    /**
     * 获取子部位列表
     *
     * @param parentId 父部位id
     */
    private void getChildPoints(final String parentId) {
        MyLog.d(TAG, "getChildPoints: parentId:" + parentId);
        changeVisibilty(true);
        mapUtil.getChildPoints(parentId)
                .subscribeWith(new Observer<List<QueryChildPointsResponse>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(List<QueryChildPointsResponse> value) {
                        mPointList = value;
                        if (mPointList != null && mPointList.size() > 0) {
                            points = new String[mPointList.size()];
                            for (int i = 0; i < mPointList.size(); i++) {
                                points[i] = mPointList.get(i).getPosition_ch();
                            }
                            selectChildPoint(parentId);
                        } else {
                            if (!isDestroyed()) {
                                new AlertDialog.Builder(SelectCheckPointActivity.this)
                                        .setTitle("错误")
                                        .setMessage("没有查询到子部位数据")
                                        .setCancelable(false)
                                        .setNegativeButton("退出", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                finish();
                                            }
                                        }).create()
                                        .show();
                            }
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        MyLog.e(TAG, "onError: ", e);
                        changeVisibilty(false);
                        if (!isFinishing()) {
                            new AlertDialog.Builder(SelectCheckPointActivity.this)
                                    .setTitle("错误" + e.getMessage())
                                    .setMessage(e.getLocalizedMessage())
                                    .create()
                                    .show();
                        }
                    }

                    @Override
                    public void onComplete() {
                        MyLog.d(TAG, "onComplete: getChildPoints Over");
                        changeVisibilty(false);
                    }
                });
    }

    /**
     * 弹出列表对话框选择子部位
     */
    private void selectChildPoint(final String parentId) {
        AlertDialog.Builder builder = new AlertDialog.Builder(SelectCheckPointActivity.this);
        builder.setTitle("请选择具体检查部位")
                .setItems(points, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        if (!"14".equals(parentId)) {
                            if (mPointList.size() <= which || which < 0)
                                return;
                            QueryChildPointsResponse child = mPointList.get(which);
                            AddMassLossRecordActivity.actionStart(SelectCheckPointActivity.this, parentId, child.getPosition_id(),
                                    child.getPosition_ch(), child.getPosition_en(), informations.get("voyageNo"),
                                    informations.get("model"), informations.get("modelCode"), informations.get("uri"));
                        } else {
                            if (mOtherList.size() <= which || which < 0)
                                return;
                            QueryOtherPointsResponse child = mOtherList.get(which);
                            AddMassLossRecordActivity.actionStart(SelectCheckPointActivity.this, parentId, child.getId(),
                                    child.getName_ch(), child.getName_en(), informations.get("voyageNo"),
                                    informations.get("model"), informations.get("modelCode"), informations.get("uri"));
                        }
                    }
                }).show();
    }

    /**
     * 启动Activity
     *
     * @param context  上下文
     * @param voyageNo 航次
     * @param model    车型
     * @param code     车型号
     * @param uri      铭牌照片路径
     */
    public static void actionStart(Context context, String voyageNo, String model, String code, String uri) {
        Intent intent = new Intent(context, SelectCheckPointActivity.class);
        intent.putExtra("voyageNo", voyageNo);
        intent.putExtra("model", model);
        intent.putExtra("modelCode", code);
        intent.putExtra("uri", uri);
        context.startActivity(intent);
    }

    private void changeVisibilty(boolean flag) {
        if (flag) {
            mProcessing.setVisibility(View.VISIBLE);
        } else {
            mProcessing.setVisibility(View.INVISIBLE);
        }
    }

}
